﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OTS.BLL;
using System.Data;
using OTS.Model;
using System.Text;

public partial class OLPC_MCTxtExport : System.Web.UI.Page
{
    #region
    public string importhead = "0";
    public string assignedhead = "0";
    private string _downloadtxt;
    public string downloadtxt
    {
        get { return _downloadtxt; }
        set { _downloadtxt = value; }
    }
    public string getUserCode()
    {
        return downloadtxt;
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CommonMethod.IsTimeOutUserCode(this, CommonModel.errorTimeOutUrl1);
            SettingRight();
            Session["dtlist"] = null;
            Session["dtassignedlist"] = null;
            InitUi();
        }
    }
    // 页面权限
    private void SettingRight()
    {
        CommonMethod comHelp = new CommonMethod();
        bool[] rightlist = SysRightBLL.GetRightByType(new string[] { 
            Session["UserCode"].ToString(), 
            Session["CoCode"].ToString(), 
            "mctxtexport"});
        if (!rightlist[0])
        { this.Page.Response.Write(String.Format("<script language='javascript'>window.parent.location.href='{0}';</script>", CommonModel.loginOut1)); }

        gv.Columns[0].Visible = rightlist[1];
        gvAssigned.Columns[0].Visible = rightlist[1];
        btnsure.Visible = rightlist[1];
    }

    // 初始化绑定
    private void InitUi()
    {
        CommonMethod.IsTimeOutUserCode(this);
        InitDataBind();
        InitAssignedDataBind();
    }
    // 已有数据
    private void InitDataBind()
    {
        DataTable tempdt = new DataTable();
        if (Session["dtlist"] != null)
        {
            tempdt = Session["dtlist"] as DataTable;
        }
        else
        {
            tempdt = AccountStatementItemBLL.GetList("");
        }
        gv.DataSource = tempdt;
        gv.DataBind();
        Session["dtlist"] = tempdt;
    }
    private void InitAssignedDataBind()
    {
        DataTable tempdt = new DataTable();
        if (Session["dtassignedlist"] != null)
        {
            tempdt = Session["dtassignedlist"] as DataTable;
        }
        else
        {
            tempdt = AccountStatementManualBLL.GetList(" len(InvioceNo)>0 and len(InvoiceNo)>0 ");
        }
        gvAssigned.DataSource = tempdt;
        gvAssigned.DataBind();
        Session["dtassignedlist"] = tempdt;
    }
    protected void gv_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
    {
        InitDataBind();
    }
    protected void gvAssigned_AfterPerformCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewAfterPerformCallbackEventArgs e)
    {
        InitAssignedDataBind();
    }

    #region Checked

    public bool IsVisibale1(string statevalue)
    {
        return "import" == statevalue;
    }
    public bool IsVisibale2(string statevalue)
    {
        return "1" == statevalue;
    }
    public bool Checked(string flagvalue)
    {
        return "1".Equals(flagvalue);
    }
    public bool Checked1()
    {
        return "1".Equals(hidimporthead.Value.ToString());
    }
    public bool Checked2()
    {
        return "1".Equals(hidassignedhead.Value.ToString());
    }

    protected void chk_CheckedChanged_gv(object sender, EventArgs e)
    {
        CheckBox chk = sender as CheckBox;
        string rowindex = chk.ToolTip;
        int index = int.Parse(rowindex);
        if (Session["dtlist"] != null)
        {
            try
            {
                DataTable tempdt = Session["dtlist"] as DataTable;
                tempdt.Rows[index - 1]["B1"] = chk.Checked ? 1 : 0;
                gv.DataSource = tempdt;
                Session["dtlist"] = tempdt;
                decimal all = 0;
                DataRow[] rwos = tempdt.Select("B1=1");
                foreach (DataRow row in rwos)
                {
                    all += decimal.Parse(row["TransactionAmount"].ToString().Trim());
                }
                lblSelectedAmountImport.Text = String.Format("{0:N2}", all);
            }
            catch (Exception ex)
            {
                Log.WritLog("chk_CheckedChanged_gv:", ex.ToString());
            }
        }
        else
        {
            chk.Checked = false;
            CommonMethod.regAlertMessage(UpdatePanel, "选择失败！", this);
        }
    }
    protected void chk_Head_CheckedChange_gv(object sender, EventArgs e)
    {
        string condition = gv.FilterExpression;
        string filtercondition = string.IsNullOrEmpty(condition) ? " 1=1 " : (condition.Trim().Length == 0 ? " 1=1 " : condition);

        CheckBox chk = sender as CheckBox;
        if (Session["dtlist"] != null)
        {
            try
            {
                DataTable tempdt = Session["dtlist"] as DataTable;
                int flag = chk.Checked ? 1 : 0;
                decimal all = 0;
                foreach (DataRow row in tempdt.Rows)
                    row["B1"] = 0;
                if (flag == 1)
                {
                    //CommonMethod.regAlertMessage(UpdatePanel, filtercondition, this);
                    DataRow[] rows = tempdt.Select(filtercondition + " and StateValue='import' ");
                    foreach (DataRow row in rows)
                    {
                        tempdt.Rows[int.Parse(row["rowindex"].ToString())-1]["B1"] = flag;
                        all += decimal.Parse(row["TransactionAmount"].ToString().Trim());
                    }

                }
                importhead = flag.ToString();
                hidimporthead.Value = flag.ToString();
                gv.DataSource = tempdt;
                gv.DataBind();
                Session["dtlist"] = tempdt;
                lblSelectedAmountImport.Text = String.Format("{0:N2}", all);
            }
            catch (Exception ex)
            {
                Log.WritLog("chk_CheckedChanged_gv:", ex.ToString());
            }
        }
        else
        {
            //chk.Checked = false;
            CommonMethod.regAlertMessage(UpdatePanel, "选择失败！", this);
        }
    }
    protected void chk_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox chk = sender as CheckBox;
        string rowindex = chk.ToolTip;
        int index = int.Parse(rowindex);
        if (Session["dtassignedlist"] != null)
        {
            try
            {
                DataTable tempdt = Session["dtassignedlist"] as DataTable;
                tempdt.Rows[index - 1]["B1"] = chk.Checked ? 1 : 0;
                Session["dtassignedlist"] = tempdt;
                decimal all = 0;
                DataRow[] rwos = tempdt.Select("B1=1");
                foreach (DataRow row in rwos)
                {
                    all += decimal.Parse(row["ApplyAmount"].ToString().Trim());
                }
                lblSelectedAmountAssigned.Text = String.Format("{0:N2}", all);
            }
            catch (Exception ex)
            {
                Log.WritLog("chk_CheckedChanged:", ex.ToString());
            }
        }
        else
        {
            chk.Checked = false;
            CommonMethod.regAlertMessage(UpdatePanel, "选择失败！", this);
        }
    }
    protected void chk_Head_CheckedChanged(object sender, EventArgs e)
    {
        string condition = gvAssigned.FilterExpression;
        string filtercondition = string.IsNullOrEmpty(condition) ? " 1=1 " : (condition.Trim().Length == 0 ? " 1=1 " : condition);
        CheckBox chk = sender as CheckBox;
        if (Session["dtassignedlist"] != null)
        {
            try
            {
                DataTable tempdt = Session["dtassignedlist"] as DataTable;
                int flag = chk.Checked ? 1 : 0;
                decimal all = 0;
                foreach (DataRow row in tempdt.Rows)
                    row["B1"] = 0;
                if (flag == 1)
                {
                    DataRow[] rows = tempdt.Select(filtercondition + " and StateValue='0' ");
                    foreach (DataRow row in rows)
                    {
                        tempdt.Rows[int.Parse(row["rowindex"].ToString()) - 1]["B1"] = flag;
                        all += decimal.Parse(row["ApplyAmount"].ToString().Trim());
                    }
                }
                assignedhead = flag.ToString();
                hidassignedhead.Value = flag.ToString();
                Session["dtassignedlist"] = tempdt;
                gvAssigned.DataSource = tempdt;
                gvAssigned.DataBind();
                lblSelectedAmountAssigned.Text = String.Format("{0:N2}", all);
            }
            catch (Exception ex)
            {
                Log.WritLog("chk_CheckedChanged:", ex.ToString());
            }
        }
        else
        {
            CommonMethod.regAlertMessage(UpdatePanel, "选择失败！", this);
        }
    }

    private string AmountImported()
    {
        string temp = "0";
        string condition = gv.FilterExpression;
        string filtercondition = string.IsNullOrEmpty(condition) ? " 1=1 " : (condition.Trim().Length == 0 ? " 1=1 " : condition);

        if (Session["dtlist"] != null)
        {
            try
            {
                DataTable tempdt = Session["dtlist"] as DataTable;
                int flag = "1".Equals(hidimporthead.Value) ? 1 : 0;
                decimal all = 0;
                    //CommonMethod.regAlertMessage(UpdatePanel, filtercondition, this);
                if (flag == 1)
                {
                    DataRow[] rows = tempdt.Select(filtercondition + " and StateValue='import' and B1='1' ");
                    foreach (DataRow row in rows)
                    {
                        all += decimal.Parse(row["TransactionAmount"].ToString().Trim());
                    }
                }
                temp = String.Format("{0:N2}", all);
                lblSelectedAmountImport.Text = temp;
            }
            catch (Exception ex)
            {
                Log.WritLog("chk_CheckedChanged_gv:", ex.ToString());
            }
        }
        CommonMethod.regAlertMessageScript(UpdatePanel,
            String.Format("showamount('tc_lblSelectedAmountImport','{0}')", temp)
            , this);

        return temp;
    }
    #endregion

    private bool CompanyCheck(DataTable dt)
    {
        if (dt != null && dt.Rows.Count > 0)
        {
            try
            {
                string coname = dt.Rows[0]["CoName"].ToString();
                foreach (DataRow row in dt.Rows)
                {
                    if (!coname.Equals(row["CoName"].ToString()))
                    {
                        CommonMethod.regAlertMessage(UpdatePanel, "一次只能选择导出一个公司！", this);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WritLog("CompanyCheck:", ex.ToString());
            }
        }
        return true;
    }
    protected void btnsure_Click(object sender, EventArgs e)
    {
        CommonMethod.IsTimeOutUserCode(this);
        string usercode = Session["UserCode"].ToString();
        int index = tc.ActiveTabIndex;
        //string filename = string.Empty;
        DataTable tempdt = new DataTable();
        List<DataRow> listdr = new List<DataRow>();
        DataTable tempsourcedt = new DataTable();
        ExportResultModel resultmodel = new ExportResultModel();
        List<ExportResultModel> modellist = new List<ExportResultModel>();
        if (index == 0)
        {
            #region 收款

            if (Session["dtlist"] != null)
            {
                tempsourcedt = Session["dtlist"] as DataTable;
            }
            if (tempsourcedt != null && tempsourcedt.Rows.Count > 0)
            {
                #region
                //int rowindex = -1;
                //gv.Columns[gv.Columns.Count - 1].Visible = true;
                //List<object> rowindexList = gv.GetSelectedFieldValues("rowindex");
                //gv.Columns[gv.Columns.Count - 1].Visible = false;
                //if (rowindexList != null)
                //{
                //    int rowcount = tempsourcedt.Rows.Count;
                //    for (int i = 0; i < rowindexList.Count; i++)
                //    {
                //        if (rowindexList[i] == null || rowindexList[i] == DBNull.Value) continue;
                //        rowindex = int.Parse(rowindexList[i].ToString());
                //        if (rowindex < rowcount && rowindex > -1)
                //        {
                //            listdr.Add(tempsourcedt.Rows[rowindex]);
                //        }
                //    }
                //}
                #endregion

                DataRow[] rows = tempsourcedt.Select("B1='1'");
                foreach (DataRow row in rows)
                    listdr.Add(row);

                if (listdr != null && listdr.Count > 0)
                {
                    tempdt = listdr.CopyToDataTable();
                    bool morecompany = CompanyCheck(tempdt);
                    if (morecompany)
                    {
                        //resultmodel = MCTxtExportBLL.BuildAdvancePaymentDimension(tempdt, usercode);
                        modellist = MCTxtExportBLL.BuildAdv(tempdt, usercode);
                    }
                }
                else
                    CommonMethod.regAlertMessage(UpdatePanel, "没有获取到选中行！", this);
            }

            #endregion
        }
        else
        {
            #region 收款匹配

            listdr = new List<DataRow>();
            tempsourcedt = new DataTable();
            if (Session["dtassignedlist"] != null)
            {
                tempsourcedt = Session["dtassignedlist"] as DataTable;
            }
            if (tempsourcedt != null && tempsourcedt.Rows.Count > 0)
            {
                DataRow[] rows = tempsourcedt.Select("B1='1'");
                foreach (DataRow row in rows)
                    listdr.Add(row);

                if (listdr != null && listdr.Count > 0)
                {
                    tempdt = listdr.CopyToDataTable();
                    bool morecompany = CompanyCheck(tempdt);
                    if (morecompany)
                    {
                        //resultmodel = MCTxtExportBLL.BuildInvoiceDimension(tempdt, usercode);
                        modellist = MCTxtExportBLL.BuildAdvInvoiceI(tempdt, usercode);
                    }
                }
                else
                    CommonMethod.regAlertMessage(UpdatePanel, "没有获取到选中行！", this);
            }

            #endregion
        }
        #region 导出文件
        bool flag = IsExportSuccess(modellist);
        if (!flag)
        {
            StringBuilder sb = new StringBuilder("导出失败！");
            foreach (ExportResultModel model in modellist)
            {
                if (model.errorlistmessage != null && model.errorlistmessage.Count > 0)
                {
                    sb.Append("未成功导出的如下：");
                    foreach (string temp in model.errorlistmessage)
                        sb.AppendFormat("{0} ", temp);
                }
            }
            CommonMethod.regAlertMessage(UpdatePanel, sb.ToString(), this);
        }
        else
        {
            if (index == 0)
            {
                Session["dtlist"] = null;
                InitDataBind();
            }
            else
            {
                Session["dtassignedlist"] = null;
                InitAssignedDataBind();
            }
            //string errormessage = sb.ToString();
            //string script = String.Format("pagereload('{0}/FilesDownLoad.aspx?filePosition=OLPCExportFiles/{1}','{2}')",
            //    GetHost(), resultmodel.filename, errormessage);
            //CommonMethod.regAlertMessageScript(UpdatePanel, script, this);
            tc.ActiveTabIndex = 2;
            StringBuilder filelisturl = new StringBuilder("");
            StringBuilder sb = new StringBuilder();
            string urltemplate = "<a href=\"../FilesDownLoad.aspx?filePosition=OLPCExportFiles/{0}\">{0}</a> <br />";
            foreach (ExportResultModel model in modellist)
            {
                if (!string.IsNullOrEmpty(model.filename))
                {
                    filelisturl.Append(string.Format(urltemplate, model.filename));
                }

                if (model.errorlistmessage != null && model.errorlistmessage.Count > 0)
                {
                    sb.Append("未成功导出的如下：");
                    foreach (string temp in model.errorlistmessage)
                        sb.AppendFormat("{0}  ", temp);
                }
            } //CommonMethod.regAlertMessage(UpdatePanel, filelisturl.ToString(), this);
            downloadtxt = filelisturl.ToString();
            if (sb.Length > 3)
            {
                CommonMethod.regAlertMessage(UpdatePanel, sb.ToString(), this);
            }
        }
        #endregion
    }

    public bool IsExportSuccess(List<ExportResultModel> modellist)
    {
        bool flag = false;
        if (modellist != null && modellist.Count > 0)
        {
            foreach (ExportResultModel model in modellist)
            {
                if (!string.IsNullOrEmpty(model.filename))
                {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }


    protected void gv_CustomJSProperties(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewClientJSPropertiesEventArgs e)
    {
        //AmountImported();
        //e.Properties["cpImportedSelectedAmount"] = 
    }
}